package alg;

import entities.Domain;
import entities.Query;
import entities.ViewGene;
import java.util.ArrayList;
import java.util.List;
import operators.QueryExecutionPlan;
import static alg.Constants.*;

/**
 *
 * @author Dragan Sahpaski
 */
public class QueryEval {

    List<QueryExecutionPlan> bestPlans;

    public List<QueryExecutionPlan> getBestPlans() {
        return bestPlans;
    }

    public double evaluateQueriesExecTime(Domain domain, List<Query> queries) {
        bestPlans = new ArrayList<QueryExecutionPlan>();
        double costForAllQueries = 0;
        for (Query query : queries) {
            double minQueryCost = MAX_VALUE;
            QueryExecutionPlan bestPlan = null;
            for (ViewGene vg : query.getUsableViews()) {
                if (vg.isTableMaterialized()) {
                    QueryExecutionPlan plan = new QueryExecutionPlan(domain, query, vg);
                    plan.executePlan();
                    double queryCost = plan.getDiskCost();
                    if (queryCost < minQueryCost) {
                        minQueryCost = queryCost;
                        bestPlan = plan;
                    }
                } // End isViewMaterialized
                if (minQueryCost == MAX_VALUE || costForAllQueries == MAX_VALUE) {
                    costForAllQueries = MAX_VALUE;
                } else {
                    costForAllQueries += minQueryCost;
                }

            } // End forall usableViews
            bestPlans.add(bestPlan);
        } // End forall Queries
        // getMinPrice of Dimension in all views in query
        // TODO
        if (costForAllQueries == 0) {
            costForAllQueries = MAX_VALUE;
        }
        return costForAllQueries;
    }
}
